{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "name": "04212.ipynb",
      "provenance": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/yananma/5_programs_per_day/blob/master/04212.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "OxPdMM3Z3P4o",
        "colab_type": "text"
      },
      "source": [
        "## 3.13 丢弃法"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "i08nJWX930DA",
        "colab_type": "text"
      },
      "source": [
        "### 3.13.2 从零开始实现"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "USEgKgPm37Sf",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "%matplotlib inline \n",
        "import torch \n",
        "import torch.nn as nn \n",
        "import numpy as np\n",
        "import d2l \n",
        "\n",
        "\n",
        "def dropout(X, drop_prob):\n",
        "    X = X.float()\n",
        "    assert 0 <= drop_prob <= 1 \n",
        "    keep_prob = 1 - drop_prob \n",
        "    \n",
        "    if keep_prob == 0:\n",
        "        return torch.zeros_like(X)\n",
        "    mask = (torch.rand(X.shape) < keep_prob).float()\n",
        "\n",
        "    return mask * X / keep_prob "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-WqWLajC4_lJ",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 50
        },
        "outputId": "fb711d5e-3b58-4130-fedb-3ca21451be30"
      },
      "source": [
        "X = torch.arange(16).view(2, 8)\n",
        "dropout(X, 0)"
      ],
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "tensor([[ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.],\n",
              "        [ 8.,  9., 10., 11., 12., 13., 14., 15.]])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bWrmno845J_D",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 50
        },
        "outputId": "58e93400-165a-4c4f-e255-3669a22cc5d4"
      },
      "source": [
        "dropout(X, 0.5)"
      ],
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "tensor([[ 0.,  0.,  4.,  0.,  0.,  0., 12.,  0.],\n",
              "        [ 0., 18., 20.,  0.,  0., 26.,  0., 30.]])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8tr_KEXy5Tqj",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 50
        },
        "outputId": "856574a3-f237-412f-e683-a5a791bbef4e"
      },
      "source": [
        "dropout(X, 1)"
      ],
      "execution_count": 6,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "tensor([[0., 0., 0., 0., 0., 0., 0., 0.],\n",
              "        [0., 0., 0., 0., 0., 0., 0., 0.]])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vMslgvPa5adl",
        "colab_type": "text"
      },
      "source": [
        "#### 1. 定义模型参数"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "4m9XLxZR5kPT",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "num_inputs, num_outputs, num_hiddens1, num_hiddens2 = 784, 10, 256, 256 \n",
        "\n",
        "W1 = torch.tensor(np.random.normal(0, 0.01, size=(num_inputs, num_hiddens1)), dtype=torch.float, requires_grad=True)\n",
        "b1 = torch.zeros(num_hiddens1, requires_grad=True)\n",
        "W2 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens1, num_hiddens2)), dtype=torch.float, requires_grad=True)\n",
        "b2 = torch.zeros(num_hiddens2, requires_grad=True)\n",
        "W3 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens2, num_outputs)), dtype=torch.float, requires_grad=True)\n",
        "b3 = torch.zeros(num_outputs, requires_grad=True)\n",
        "\n",
        "params = [W1, b1, W2, b2, W3, b3]"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "oUop_e2e62su",
        "colab_type": "text"
      },
      "source": [
        "#### 2. 定义模型"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "klZbDm-D6_96",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "drop_prob1, drop_prob2 = 0.2, 0.5 \n",
        "\n",
        "def net(X, is_training=True):\n",
        "    X = X.view(-1, num_inputs)\n",
        "    H1 = (torch.matmul(X, W1) + b1).relu()\n",
        "    if is_training:\n",
        "        H1 = dropout(H1, drop_prob1)\n",
        "    H2 = (torch.matmul(H1, W2) + b2).relu()\n",
        "    if is_training:\n",
        "        H2 = dropout(H2, drop_prob2)\n",
        "    return torch.matmul(H2, W3) + b3 "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "NTE7PmN971oR",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "def evaluate_accuracy(data_iter, net):\n",
        "    acc_sum, n = 0.0, 0 \n",
        "    for X, y in data_iter:\n",
        "        if isinstance(net, torch.nn.Module):\n",
        "            net.eval()\n",
        "            acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()\n",
        "            net.train()\n",
        "        else:\n",
        "            if ('is_training' in net.__code__.co_varnames):\n",
        "                acc_sum += (net(X, is_training=False).argmax(dim=1) == y).float().sum()\n",
        "            else:\n",
        "                acc_sum += (net(X).argmax(dim=1) == y).float().sum().item()\n",
        "        n += y.shape[0]\n",
        "    return acc_sum / n "
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "o6Gf_adu_jFz",
        "colab_type": "text"
      },
      "source": [
        "#### 3. 训练和测试模型"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "wjtTr7vc9ag0",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 101
        },
        "outputId": "07c41ac6-ad86-43c2-808b-cddb8edb9dbc"
      },
      "source": [
        "num_epochs, lr, batch_size = 5, 100.0, 256 \n",
        "loss = torch.nn.CrossEntropyLoss()\n",
        "train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)\n",
        "d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, params, lr)"
      ],
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "epoch 1, loss 1.1633, train acc 0.547, test acc 0.746\n",
            "epoch 2, loss 0.5898, train acc 0.784, test acc 0.768\n",
            "epoch 3, loss 0.4866, train acc 0.825, test acc 0.833\n",
            "epoch 4, loss 0.4475, train acc 0.838, test acc 0.781\n",
            "epoch 5, loss 0.4173, train acc 0.848, test acc 0.843\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "id9y_gXt97L6",
        "colab_type": "text"
      },
      "source": [
        "### 3.13.3 简洁实现"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "cSvd2s-m-I9n",
        "colab_type": "code",
        "colab": {}
      },
      "source": [
        "net = nn.Sequential(\n",
        "    d2l.FlattenLayer(), \n",
        "    nn.Linear(num_inputs, num_hiddens1), \n",
        "    nn.ReLU(), \n",
        "    nn.Dropout(drop_prob1), \n",
        "    nn.Linear(num_hiddens1, num_hiddens2),\n",
        "    nn.ReLU(), \n",
        "    nn.Dropout(drop_prob2), \n",
        "    nn.Linear(num_hiddens2, 10)\n",
        ")\n",
        "\n",
        "for param in net.parameters():\n",
        "    nn.init.normal_(param, mean=0, std=0.01)"
      ],
      "execution_count": 0,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zDor2ibN-0eh",
        "colab_type": "code",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 101
        },
        "outputId": "2082ffc9-770d-41c8-a134-1541536c5afe"
      },
      "source": [
        "optimizer = torch.optim.SGD(net.parameters(), lr=0.5)\n",
        "d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)"
      ],
      "execution_count": 15,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "epoch 1, loss 1.1184, train acc 0.563, test acc 0.732\n",
            "epoch 2, loss 0.5849, train acc 0.784, test acc 0.805\n",
            "epoch 3, loss 0.4855, train acc 0.823, test acc 0.838\n",
            "epoch 4, loss 0.4415, train acc 0.838, test acc 0.824\n",
            "epoch 5, loss 0.4131, train acc 0.848, test acc 0.842\n"
          ],
          "name": "stdout"
        }
      ]
    }
  ]
}